package com.langerra.server.channel.impl;

import com.google.appengine.api.memcache.MemcacheService;
import com.langerra.server.channel.NamedCounter;

public class AppEngineCounter
		implements NamedCounter {

	final MemcacheService service;
	final String key;

	public AppEngineCounter(
			MemcacheService service,
			String key) {
		this.key = key;
		this.service = service;
		this.service.increment(key, 0L, 0L);
	}

	@Override
	public long get() {
		return (Long) service.get(key);
	}

	@Override
	public long getAndAdd(
			long delta) {
		return service.increment(key, delta) - delta;
	}

	@Override
	public long getAndDecrement() {
		return getAndAdd(-1L);
	}

	@Override
	public long getAndIncrement() {
		return getAndAdd(+1L);
	}

	@Override
	public long getAndSet(
			long value) {
		long old = get();
		service.put(key, value);
		return old;
	}
}
